package model

import (
	"github.com/jinzhu/gorm"
	"naio/db/mysql"
)

// backend后台管理员
type AdminModel struct {
	Model
	Username string      `json:"username"` // 用户名
	Password string      `json:"password"` // 密码
	Email    string      `json:"email"`    // 邮箱
	Mobile   string      `json:"mobile"`   // 手机号
	Avatar   string      `json:"avatar"`   // 头像
	Status   int         `json:"status"`   // 状态:0禁用,1启用
	Role     []RoleModel `gorm:"many2many:admin_role;foreignkey:Id;association_foreignkey:Id;association_jointable_foreignkey:role_id;jointable_foreignkey:admin_id;" json:"role"`
	//admin_tag表默认admin_id字段对应admin表id.role_id字段对应role表id
}

func (AdminModel) TableName() string {
	return "admin"
}

func FetchAdmin(username string) (*AdminModel, error) {
	admin := &AdminModel{}
	db := mysql.GetMysqlPool().GetMysqlDB()
	if err := db.Where("username=?", username).First(&admin).Error; err != nil {
		return nil, err
	}
	return admin, nil
}

func FetchAuthInfo(id int) (*AdminModel, error) {
	admin := &AdminModel{}
	db := mysql.GetMysqlPool().GetMysqlDB()
	if err := db.Where("id=?", id).First(&admin).Error; err != nil {
		return nil, err
	}

	if err := db.Model(&admin).Related(&admin.Role, "role").Find(&admin).Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return admin, nil
}
